<qiniu-upload>

  <button onclick={fn.select} ref="uploadBtn">选择文件</button>

  <script>
  var tag = this;
  tag.cf = {
    // 多个文件上传
    multiple: opts.multiple || false,
    // 允许上传的文件类型accept=".jpg,.gif.."
    accept: opts.accept.split(','),
    // 上传需要的token
    token: opts.token,
    // 上传重试次数
    retry: opts.retry || 1,
    // debug
    debug: opts.debug || false,
    // domain 上传域名
    domain: opts.domain,
    // 上传域名下的子目录
    folder: opts.folder || 'dev/temp'
  };
  // 上传成功or失败的文件列表
  tag.uploadedList = [];
  tag.failedList = [];
  tag.fn = {
    select: function(){
      if(!tag.qiniu){
        return alert('还在初始化中稍后点击');
      }
      tag.qiniu.chooseFile();
    }
  };
  tag.on('mount', function(){
    // 加载qiniu sdk
    pip.load(tag.app.data.qiniu)
    .on('done', function(){
      tag.qiniu = new Qiniu.UploaderBuilder()
      .debug(tag.cf.debug)
      .domain('http://upload.qiniu.com/')
      .retry(tag.cf.retry)
      .multiple(tag.cf.multiple)
      .accept(tag.cf.accept)
      .tokenFunc(function(setToken){
        setToken(tag.cf.token);
      })
      .listener({
        onReady: function(task){
          tag.refs.uploadBtn.disabled = true;
          opts.onReady && opts.onReady(task);
        },
        onStart: opts.onStart || function(){},
        onTaskProgress: opts.onProgress || function(){},
        onTaskGetKey: function(task){
          var
            file = btoa(
              task.file.name +
              task.file.size +
              task.file.lastModified
            ),
            ext = task.file.name.split('.').pop();
          return tag.cf.folder+'/'+file+'.'+ext;
        },
        onTaskSuccess: function(task){
          tag.uploadedList.push({
            name: task.file.name,
            url: tag.cf.domain+'/'+task.result.key
          });
          opts.onSuccess &&
          opts.onSuccess(tag.uploadedList, opts.item||{});
        },
        onTaskRetry: opts.onRetry || function(){},
        onTaskFail: function(task){
          tag.failedList.push({
            name: task.file.name
          });
          opts.onFail &&
          opts.onFail(task, tag.failedList);
        },
        onFinish: function(task){
          tag.refs.uploadBtn.disabled = false;
          opts.onFinish && opts.onFinish(task);
        }
      }).build();
    });
  });
  </script>

</qiniu-upload>


<qiniu>

  <style scoped>
    qiniu{padding: 20px;}
    .u-inline{width: auto; display: inline-block;}
  </style>

  <!-- 七牛需要登录后才能操作 -->
  <login-required for="h5"></login-required>

  <select class="c-field u-inline" onchange={fn.selectDomain}>
    <option each={domainList}
            selected={parent.domainSelected.url==url}
            value={url}>{domainHelper[name]}</option>
  </select>
  <select class="c-field u-inline" ref="env">
    <option each={env in envList} value="{env}">{envHelper[env]}</option>
  </select>
  <input class="c-field u-inline" type="text" ref="folder" placeholder="自定义目录(默认为temp)">
  <button class="c-button" onclick={fn.selectFile} ref="upload-btn">
    选择文件
    [<span each={ext in acceptList}>*{ext} </span>]
  </button>
  <span>{message}</span>

  <!-- 上传成功列表 -->
  <p if={uploadedList.length}>
    <dl>
      <dd each={uploadedList}>
        {name}
        <input onclick="this.select()" class="c-field u-inline" style="width: 50%" type="text" value={url}>
        <a class="c-button" href="{url}" target="_blank">查看</a>
      </dd>
    </dl>
  </p>

  <!-- 上传失败列表 -->
  <p if={failedList.length}>
    <strong>上传失败</strong>
    <ul class="c-list c-list--inline">
      <li class="c-list__item" each={failedList}>{name}</li>
    </ul>
  </p>

  <script>

  // 默认上传路径
  this.domainSelected = {
    name: 'attachments',
    url: 'http://7xwb9d.com2.z0.glb.qiniucdn.com'
  };

  this.domainHelper = {
    pics: '普通图片',
    album: '相册',
    avatar: '头像',
    static: '静态资源文件',
    private: '受保护文件',
    download: '下载文件',
    "app-resource": 'APP资源文件',
    attachments: '附件文件'
  };

  this.envHelper = {
    dev: '开发环境',
    test: '测试环境',
    production: '部署环境'
  };

  // 可上传文件类型
  this.acceptList = ['.jpg','.png', '.gif', '.js','.css'];

  // 上传成功文件
  this.uploadedList = [];

  // 失败文件
  this.failedList = [];

  // 目录列表
  this.envList = ['dev', 'test', 'production'];
  this.folder = 'temp';

  this.fn = {
    selectDomain: (e) => {
      for(let domain of this.domainList){
        if(domain.url === e.target.value){
          this.domainSelected = domain;
        }
      }
    },
    selectFile: (e) => {
      this.message = '';
      if(!this.uploader){
        this.message = '还在初始化中稍后点击';
      }
      this.uploader.chooseFile();
    }
  };

  this.on('mount', () => {
    this.domainList = [];
    this.domainObj = {
      pics: 'http://pics.sosho.cn',
      album: 'http://album.sosho.cn',
      avatar: 'http://avatar.sosho.cn',
      static: 'http://static.sosho.cn',
      private: 'http://qiniu.private.sosho.cn',
      download: 'http://download.sosho.cn',
      "app-resource": 'http://app-resource.sosho.cn',
      attachments: 'http://7xwb9d.com2.z0.glb.qiniucdn.com'
    };
    for(let k in this.domainObj){
      this.domainList.push({
        name: k, url: this.domainObj[k]
      });
    }

    // 初始化uploader
    app.loadResource('qiniu')
    .then(() => {
      this.uploader = new Qiniu.UploaderBuilder()
      .debug(false)
      .domain('http://upload.qiniu.com/')
      .retry(1)
      .auto(true)
      .multiple(true)
      .accept(this.acceptList)
      .tokenFunc((setToken, task) => {
        app.api.h5('GET', 'api/tool/upload_token', {
          bucket: this.domainSelected.name
        }).done(resp => {
          if(resp.errno != 0){
            return this.update({
              message: resp.errmsg
            })
          }
          setToken(resp.data.qiniu_token);
        });
      })
      .listener({
        onReady: tasks => {
          this.refs['upload-btn'].disabled = true;
        },
        onStart(tasks){},
        onTaskProgress: task => {
          this.update({
            message: `(${task.file.name}) 上传中...${task.progress}%`
          });
        },
        onTaskGetKey: task => {
          let
            env = this.refs.env.value,
            folder = this.refs.folder.value || this.folder,
            file = btoa(task.file.name+task.file.size+task.file.lastModified),
            ext = task.file.name.split('.').pop();
          return `${env}/${folder}/${file}.${ext}`;
        },
        onTaskSuccess: task => {
          this.uploadedList.push({
            name: task.file.name,
            url: this.domainSelected.url+'/'+
              (task.result.key||task.result.hash),
          });
          this.message = `(${task.file.name}) 上传成功!`;
          this.update();
        },
        onTaskRetry: task => {
          this.update({
            message: `(${task.file.name}) 尝试重新上传`
          });
        },
        onTaskFail: task => {
          this.failedList.push({
            name: task.file.name
          });
          this.update();
        },
        onFinish: tasks => {
          this.refs['upload-btn'].disabled = false;
        }
      }).build();
    });

    this.update();
  });
  </script>

</qiniu>
